// Copyright 2010 Google Inc. All Rights Reserved.

package com.google.android.apps.wakemewhere;

import static android.content.Context.LOCATION_SERVICE;

import java.util.List;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;

/**
 * @author baran@google.com (Baran Ozgul)
 */
public class ProximityAlertAlarmArbiter implements AlarmArbiter {

	public static final float DEFAULT_PROXIMITY_RADIUS = 1000.0f;
	public static final String PROXIMITY_ALERT = "com.google.android.apps.wakemewhere.PROXIMITY_ALERT";
	private final LocationManager locationManager;
	private final Context context;

	public ProximityAlertAlarmArbiter(Context context) {
		this(context, (LocationManager) context.getSystemService(LOCATION_SERVICE));
	}

	public ProximityAlertAlarmArbiter(Context context, LocationManager locationManager) {
		this.context = context;
		this.locationManager = locationManager;
	}
	
	public void removeProximityAlertForAlarm(Context context, long alarmId) {
		PendingIntent pendingIntent = getPendingIntentForAlarmId(context, alarmId);
		locationManager.removeProximityAlert(pendingIntent);	
	}

	public void addProximityAlertForAlarm(Context context, Alarm alarm) {
		PendingIntent pendingIntent = getPendingIntentForAlarmId(context, alarm.getId());
		locationManager.addProximityAlert(alarm.getLatitude(), alarm.getLongitude(), DEFAULT_PROXIMITY_RADIUS, -1, pendingIntent);
	}

	private static PendingIntent getPendingIntentForAlarmId(Context context, long alarmId) {
		Intent intent = new Intent();
		intent.setAction(PROXIMITY_ALERT);
		intent.setClass(context, ProximityIntentReceiver.class);
		intent.setData(Alarms.uriForId(alarmId));  // set data to guarantee PendingIntent uniqueness. 
		intent.putExtra(IntentExtras.ALARM_ID, alarmId);
  		PendingIntent proximityIntent = PendingIntent.getBroadcast(context, (int) (alarmId), intent,
				PendingIntent.FLAG_CANCEL_CURRENT);
		return proximityIntent;
	}
	
	public void removeAlarms(List<Alarm> alarms) {
		for (Alarm alarm : alarms) {
			removeProximityAlertForAlarm(context, alarm.getId());	
		}
	}
	
	public void addAlarms(List<Alarm> alarms) {
		for (Alarm alarm : alarms) {
			if (alarm.isEnabled()) {
				addProximityAlertForAlarm(context, alarm);			
			}
		}		
	}
	
	public void setAlarms(List<Alarm> alarms) {
		removeAlarms(alarms);
		addAlarms(alarms);
	}

	public void start() {
	}
}